import { loginByUsername, logout, getUserInfo } from '../../api/login'
import { getToken, setToken, removeToken, setRoles, getRoles, removeRoles } from '../../utils/auth'
// import logo from '@/assets/img/logo.jpg'
const user = {
  state: {
    forcedLogin: true,
		hasLogin: false,
		userName: "",
		openid: null,
    ///////////////////////////////////
    user: null,
    status: '',
    code: '',
    token: getToken(),
    name: '',
    // avatar: logo,
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    },
    axiosTimeout: 5000 // 默认超时的时间为5000ms
  },

  mutations: {
    login(state, userName) {
      state.userName = userName || '新用户';
      state.hasLogin = true;
    },
    logout(state) {
        state.userName = "";
        state.hasLogin = false;
    },
    setOpenid(state, openid) {
      state.openid = openid
    },
    ///////////////////////////////////
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_AxiosTimeout: (state, axiosTimeout) => {
      state.axiosTimeout = axiosTimeout
    }
  },

  actions: {
    getUserOpenId: async function ({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.openid) {
					resolve(state.openid)
				} else {
					uni.login({
						success: (data) => {
							commit('login')
							setTimeout(function () { //模拟异步请求服务器获取 openid
								const openid = '123456789'
								console.log('uni.request mock openid[' + openid + ']');
								commit('setOpenid', openid)
								resolve(openid)
							}, 1000)
						},
						fail: (err) => {
							console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
							reject(err)
						}
					})
				}
			})
    },
    ///////////////////////////////////
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      // const username = userInfo.account.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(userInfo).then(data => {
          let [error, res]  = data;
          commit('SET_TOKEN', res.data.token)
          commit('SET_USER', res.data.user)
					uni.setStorageSync('token', res.data.token);
          resolve(res.data)
        }).catch(error => {
					console.log(error);
          reject(error.data)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        // getUserInfo(state.token).then(response => {
        //   if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
        //     reject('error')
        //   }
        //   const data = response.data

        //   if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
        //     commit('SET_ROLES', data.roles)
        //   } else {
        //     reject('getInfo: roles must be a non-null array !')
        //   }

        //   commit('SET_NAME', data.name)
        //   commit('SET_AVATAR', data.avatar)
        //   commit('SET_INTRODUCTION', data.introduction)
        //   resolve(response)
        // }).catch(error => {
        //   reject(error)
        // })
        commit('SET_ROLES', JSON.parse(getRoles()) ) 
        resolve()
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          removeRoles()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        removeRoles()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({ commit }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          // commit('SET_AVATAR', logo + '?' + +new Date())
          commit('SET_INTRODUCTION', data.introduction)
          resolve()
        })
      })
    }
  }
}

export default user
